const path = require('path')
const artTemplate = require('art-template')
const { rmSlash, rmStartSlash, parseQuery, firstUpcase } = require('../utils')
const { readFile, writeFile, isExists, delFile } = require('../utils/file')

/**
 * 校验生成代码模板参数
 * @param {Object} params 参数
 */
// const validTemParams = (params) => {

// }

/**
 * 初始化API参数
 * @param {Object} params 参数
 */
const initHandlerParams = (handlerList) => {
  const temParams = {}
  const list = handlerList.map(item => {
    temParams[item.type] = item
    item.url = rmStartSlash(item.url)
    item.params = item.method === 'get' ? 'params' : 'data'
    if (!item.apiName) {
      item.apiName = 'api' + firstUpcase(item.type) + rmSlash(item.url)
    }
    return item
  })
  temParams.list = list
  return temParams
}

/**
 * 初始化搜索
 * @param {Object} params
 * @returns {Object}
 */
const initSearchParams = params => {
  const temParams = params.map(item => {
    if (item.mode === 'remote' && !item.apiName) {
      const searchUrl = rmStartSlash(item.searchUrl)
      const searchName = rmSlash(searchUrl)
      item.searchUrl = searchUrl
      item.apiName = 'apiGet' + searchName
      item.methodName = 'confirmGet' + searchName
      item.selectListName = searchName[0].toLowerCase() + searchName.slice(1) + 'List'
    }
    return item
  })
  console.log(params);
  return temParams
}

/**
 * 设置方法
 * @param {Object} params
 */
// const initMethodParams = (params) => {
//   params.handler = {}
//   params.handlerList.forEach(item => {
//     params.handler[item.method] = item
//     item.url = rmStartSlash(item.url)
//     item.params = item.method === 'get' ? 'params' : 'data'
//     if (!item.apiName) {
//       item.apiName = rmSlash(item.url)
//     }
//     return item
//   })
//   return params
// }

/**
 * 保存文件
 * @param {Object} param.filePath 文件读取路径
 * @param {Object} param.needSave 文件是否写入
 * @param {Object} param.savePath 文件写入路径
 * @param {Object} temParams 模板参数
 * @returns Promise对象
 */
const saveFile = async ({ filePath = '/', savePath = '/', needSave = true } = {}, temParams) => {
  try {
    if (needSave) {
      const data = await readFile(filePath)
      const file = artTemplate.render(data.toString(), temParams)
      await writeFile(savePath, file)
    } else {
      const hasFile = await isExists(savePath)
      if (hasFile) {
        delFile(savePath)
      }
    }
    return true
  } catch (error) {
    console.log(error)
    return false
  }
}

/**
 * 初始化参数
 * @param {Object} params 参数
 * @returns params
 */
const initParams = (params) => {
  let { table, handlerList, columns, search, formLabelList, popupDetail } = params
  const handler = initHandlerParams(handlerList)
  search = initSearchParams(search)
  return { columns, search, formLabelList, popupDetail, table, handler }
}

/**
 * 生成模板文件
 * @param {object} params 模板参数
 * @param {Function} cb 回调函数
 */
const createFile = (params, cb) => {
  // if (!validTemParams(params)) {
  // return cb({code: 500,msg: '参数不正确'})
  // }
  const temParams = initParams(params)
  const indexFile = {
    filePath: path.join(__dirname, '../public/index.art'),
    savePath: path.join(__dirname, '../file/index.vue'),
    needSave: temParams.handler.get ? true : false
  }
  const componentFile = {
    filePath: path.join(__dirname, '../public/components/detail.art'),
    savePath: path.join(__dirname, '../file/components/detail.vue'),
    needSave: temParams.popupDetail.hasPopup === 1
  }
  const apiFile = {
    filePath: path.join(__dirname, '../public/api/index.art'),
    savePath: path.join(__dirname, '../file/api/index.js'),
    needSave: temParams.handler.list.length > 0
  }
  Promise.all([
    saveFile(indexFile, temParams),
    saveFile(componentFile, temParams),
    saveFile(apiFile, temParams)])
    .then(success => {
      if (success.every(item => item)) {
        console.log(success)
      }
    })
    .catch(error => cb(error))
}

/**
 * 处理模板字符串
 */
const disposeTem = (params, cb) => {
  const createParams = parseQuery(params)
  createFile(createParams, cb)
}

module.exports = { disposeTem }
